package game.screens;

import game.Game;
import game.Main;
import game.util.TileGraphics;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.gui.TextField;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import session.Session;

/**
 * Log in screen
 */
public class StartupScreen extends BasicGameState {
   
   private static final int ID = 0;
   private TextField ipField;
   private TextField portField;
   private TextField nameField;
   private String error;
   /**
    * Keyboard input
    */
   private Input input;
   private Game game;
   
   public StartupScreen(Game game) {
      this.game = game;
      error = new String();
   }
   
   /**
    * Starts up the screen
    */
   @Override
   public void init(GameContainer container, StateBasedGame game) throws SlickException {
      input = container.getInput();
      ipField = new TextField(container, container.getDefaultFont(), 0, 100, Main.WIDTH, 25);
      ipField.setText("localhost");  
      portField = new TextField(container, container.getDefaultFont(), 0, 200, Main.WIDTH, 25);
      portField.setText("4444");
      nameField = new TextField(container, container.getDefaultFont(), 0, 300, Main.WIDTH, 25);
      nameField.setText("Name");
   }

   /**
    * Rendering. Called based on framerate.
    */
   @Override
   public void render(GameContainer container, StateBasedGame arg1, Graphics g) throws SlickException {
      ipField.render(container, g);
      portField.render(container, g);
      nameField.render(container, g);
      g.drawString(error, 10, 10);
   }

   /**
    * Update (is called much rare than render)
    */
   @Override
   public void update(GameContainer container, StateBasedGame arg1, int arg2) throws SlickException {
      if (input.isKeyPressed(Input.KEY_ENTER)) {
         try {
            game.setSession(new Session(game));
            game.getSession().init(ipField.getText(), Integer.valueOf(portField.getText()), nameField.getText());
            game.getSession().start();
         } catch (Exception e) {
            error = "Connection failed";
         }
         
      }
   }

   @Override
   public int getID() {
      return ID;
   }
   
}
